<?php

namespace App\Http\Controllers\Api;

use App\Models\Club;
use App\Models\Technician;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SearchController extends Controller
{
    public function hotKeyword()
    {

    }

    public function search(Request $request)
    {
        $type = $request->type;
        $q = $request->q;
        if (empty(trim($q))) {
            return api('没有输入任何关键字');
        }
        if ($type == 'club') {
            $result = $this->searchClubFromDatabase($q);
        } elseif ($type == 'technician') {
            $result = $this->searchTechnicianFromDatabase($q);
        } else {
            return api('暂不支持全局搜索');
        }

        return api(RET_OK, MSG_OK, $result);

    }

    private function searchClubFromDatabase($q)
    {
        $q = "%" . $q . "%";
        $collection = Club::query()->where(function ($query) use ($q) {
            $query->where('name', 'like', $q)->orWhere('short_name', 'like', $q);
        })->get(['key', 'name as text']);

        return $collection->toArray();
    }

    private function searchTechnicianFromDatabase($q)
    {
        $q = "%" . $q . "%";
        $collection = Technician::query()->where(function ($query) use ($q) {
            $query->where('name', 'like', $q)->orWhere('short_name', 'like', $q);
        })->get(['key', 'name as text']);

        return $collection->toArray();
    }
}
